﻿using AutoMapper;
using BS.Domain.RBAC;
using BS.Infra;
using BS.Infra.Interface;
using BS.Infra.Repository;
using MediatR;

namespace BS.Write.Api.Handler.RBAC
{
    public class AddAddRoleToPermissionsCommandHandler:IRequestHandler<AddRoleToPermissionsCommand, ApiResult>
    {
        private readonly ILogger<AddAddRoleToPermissionsCommandHandler> _logger;

        private readonly IPermissionsRepository _permissionsRepository;

        private readonly IRoleRepository _roleRepository;
         
        private readonly IMapper _mapper;

        public AddAddRoleToPermissionsCommandHandler(IPermissionsRepository permissionsRepository)
        {
            _permissionsRepository = permissionsRepository;
        }

        public AddAddRoleToPermissionsCommandHandler(ILogger<AddAddRoleToPermissionsCommandHandler> logger, IRoleRepository roleRepository, IMapper mapper, IPermissionsRepository permissionsRepository)
        {
            _logger = logger;
            _roleRepository = roleRepository;
            _mapper = mapper;
           
        }
        public async Task<ApiResult> Handle(AddRoleToPermissionsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var rolesDto = _mapper.Map<Role>(request);
                var result =await _roleRepository.InsertRoleWithPermissions(rolesDto, request.PermissionIds);
                var resultAll = await _roleRepository.GetAllAsync(x => x.IsDeleted == false && x.RoleName==request.RoleName);
                return await Task.FromResult(ApiResult.Ok(resultAll));

            }
            catch (Exception ex)
            {
               
                _logger.LogError(ex, "AddAddRoleToPermissionsCommandHandler");
                return await Task.FromResult(ApiResult.Fail(ex.Message));
            }
        }
    }
}
public class AddRoleToPermissionsCommand:IRequest<ApiResult>
{

    public string RoleName { get; set; } = string.Empty;

    public int[] PermissionIds { get; set; } = new int[] { };
}